using System;
using System.Collections.Generic;
using CxRomos.Core.DataAccess;
using CxRomos.Core.DataAccess.Implementation;
using CxRomos.Core.Domain;
using CxRomos.Core.Domain.Entities;
using CxRomos.Core.Services.Implementation;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;

namespace CxRomos.Core.Tests.Integration {
    [TestFixture]
    public class CreateDatabaseSchema : RepositoryBase {
        [Test]
        public void CreateDatabaseSchemaFluently() {
            Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString("server=.;trusted_connection=yes;database=cxromos"))
                .Mappings(x => x.FluentMappings.AddFromAssemblyOf<Account>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
                .BuildSessionFactory();

            IAccountRepository accountRepository = new AccountRepository();

            const string email = "acexman@gmail.com";

            var account = new Account {
                FirstName = "ace",
                LastName = "xman",
                Username = "ace",
                Email = email,
                Password = "ace".Encrypt("ace"),
                CreateDate = DateTime.Now,
                LastUpdateDate = DateTime.Now,
                BirthDate = new DateTime(1974, 9, 6),
                EmailVerified = true
            };

            accountRepository.SaveAccount(account);
            accountRepository.CommitChanges();

            var permissions = new List<Permission> {
                                                       new Permission {Name = "PUBLIC"},
                                                       new Permission {Name = "ADMINISTRATOR"},
                                                       new Permission {Name = "MODERATOR"}
                                                   };

            BeginTransaction();
            foreach (var permission in permissions) {
                NHibernateSession.SaveOrUpdate(permission);
            }
            CommitChanges();

            var ap = new AccountPermission {
                                               AccountId = account.AccountId,
                                               Permission = permissions[0]
                                           };

            BeginTransaction();
            NHibernateSession.SaveOrUpdate(ap);
            CommitChanges();
        }
    }
}